package com.taobao.yugong.common.utils;

import com.taobao.yugong.YuGongLauncher;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.redisson.Redisson;
import org.redisson.api.RBucket;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.TimeUnit;

public class RedisUtils {

    private static final Logger LOGGER = LoggerFactory.getLogger(RedisUtils.class);

    private static String host;
    private static String port;
    private static String password;

    static {
        String conf = "classpath:yugong.properties";
        PropertiesConfiguration config = new PropertiesConfiguration();
        try {
            config.load(YuGongLauncher.class.getClassLoader().getResourceAsStream(conf));
            host = config.getString("yugong.redis.host");
            port = config.getString("yugong.redis.port");
            password = config.getString("yugong.redis.password");
        } catch (Exception e) {
            LOGGER.error("加载配置文件异常:{}", e);
        }
    }

    private volatile RedissonClient redissonClient;

    public RedissonClient getRedissonClient() {
        if (null == redissonClient) {
            synchronized (RedisUtils.class) {
                if (null == redissonClient) {
                    Config config = new Config();
                    config.useSingleServer().setDatabase(0);
                    config.useSingleServer().setPassword(password);
                    config.useSingleServer().setTimeout(10000);
                    config.useSingleServer().setAddress("redis://" + host + ":" + port);
                    redissonClient = Redisson.create(config);
                }
            }
        }
        return redissonClient;
    }

    public String getString(String key) {
        RBucket<Object> result = getRedissonClient().getBucket(key);
        return result.get().toString();
    }

    public void setString(String key, Object value) {
        RBucket<Object> result = getRedissonClient().getBucket(key);
        if (!result.isExists()) {
            result.set(value, 5, TimeUnit.MINUTES);
        }
    }

}
